﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.MountAndBlade.View.ViewSubModule
// Assembly: TaleWorlds.MountAndBlade.View, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 61152EB8-513B-4D4A-8AC0-0D1465C6CF6C
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\Modules\Native\bin\Win64_Shipping_Client\TaleWorlds.MountAndBlade.View.dll

using System;
using System.Collections.Generic;
using System.IO;
using TaleWorlds.Core;
using TaleWorlds.Engine;
using TaleWorlds.Engine.InputSystem;
using TaleWorlds.Engine.Options;
using TaleWorlds.InputSystem;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ModuleManager;
using TaleWorlds.MountAndBlade.GameKeyCategory;
using TaleWorlds.MountAndBlade.View.Screens;
using TaleWorlds.MountAndBlade.View.Tableaus;
using TaleWorlds.ScreenSystem;

#nullable disable
namespace TaleWorlds.MountAndBlade.View
{
  public class ViewSubModule : MBSubModuleBase
  {
    private Dictionary<Tuple<Material, BannerCode>, Material> _bannerTexturedMaterialCache;
    private GameStateScreenManager _gameStateScreenManager;
    private bool _newGameInitialization;
    private static ViewSubModule _instance;
    private bool _initialized;

    public static Dictionary<Tuple<Material, BannerCode>, Material> BannerTexturedMaterialCache
    {
      get => ViewSubModule._instance._bannerTexturedMaterialCache;
      set => ViewSubModule._instance._bannerTexturedMaterialCache = value;
    }

    public static GameStateScreenManager GameStateScreenManager
    {
      get => ViewSubModule._instance._gameStateScreenManager;
    }

    private void InitializeHotKeyManager(bool loadKeys)
    {
      HotKeyManager.Initialize(new PlatformFilePath(EngineFilePaths.ConfigsPath, "BannerlordGameKeys.xml"), !ScreenManager.IsEnterButtonRDown);
      HotKeyManager.RegisterInitialContexts((IEnumerable<GameKeyContext>) new List<GameKeyContext>()
      {
        (GameKeyContext) new GenericGameKeyContext(),
        (GameKeyContext) new GenericCampaignPanelsGameKeyCategory(),
        (GameKeyContext) new GenericPanelGameKeyCategory(),
        (GameKeyContext) new ArmyManagementHotkeyCategory(),
        (GameKeyContext) new BoardGameHotkeyCategory(),
        (GameKeyContext) new ChatLogHotKeyCategory(),
        (GameKeyContext) new CombatHotKeyCategory(),
        (GameKeyContext) new CraftingHotkeyCategory(),
        (GameKeyContext) new FaceGenHotkeyCategory(),
        (GameKeyContext) new InventoryHotKeyCategory(),
        (GameKeyContext) new PartyHotKeyCategory(),
        (GameKeyContext) new MapHotKeyCategory(),
        (GameKeyContext) new MapNotificationHotKeyCategory(),
        (GameKeyContext) new MissionOrderHotkeyCategory(),
        (GameKeyContext) new MultiplayerHotkeyCategory(),
        (GameKeyContext) new ScoreboardHotKeyCategory(),
        (GameKeyContext) new ConversationHotKeyCategory(),
        (GameKeyContext) new CheatsHotKeyCategory(),
        (GameKeyContext) new PhotoModeHotKeyCategory(),
        (GameKeyContext) new PollHotkeyCategory()
      }, loadKeys);
    }

    private void InitializeBannerVisualManager()
    {
      if (BannerManager.Instance != null)
        return;
      BannerManager.Initialize();
      BannerManager.Instance.LoadBannerIcons(ModuleHelper.GetModuleFullPath("Native") + "ModuleData/banner_icons.xml");
      foreach (string modulesName in Utilities.GetModulesNames())
      {
        ModuleInfo moduleInfo = ModuleHelper.GetModuleInfo(modulesName);
        if (moduleInfo != null && !moduleInfo.IsNative)
        {
          string str = moduleInfo.FolderPath + "/ModuleData/banner_icons.xml";
          if (File.Exists(str))
            BannerManager.Instance.LoadBannerIcons(str);
        }
      }
    }

    protected override void OnSubModuleLoad()
    {
      base.OnSubModuleLoad();
      ViewSubModule._instance = this;
      this.InitializeHotKeyManager(false);
      this.InitializeBannerVisualManager();
      CraftedDataViewManager.Initialize();
      ScreenManager.OnPushScreen += new ScreenManager.OnPushScreenEvent(this.OnScreenManagerPushScreen);
      this._gameStateScreenManager = new GameStateScreenManager();
      Module.CurrentModule.GlobalGameStateManager.RegisterListener((IGameStateManagerListener) this._gameStateScreenManager);
      MBMusicManager.Create();
      TextObject coreContentDisabledReason = new TextObject("{=V8BXjyYq}Disabled during installation.");
      if (Utilities.EditModeEnabled)
        Module.CurrentModule.AddInitialStateOption(new InitialStateOption("Editor", new TextObject("{=bUh0x6rA}Editor"), -1, (Action) (() => MBInitialScreenBase.OnEditModeEnterPress()), (Func<(bool, TextObject)>) (() => (Module.CurrentModule.IsOnlyCoreContentEnabled, coreContentDisabledReason))));
      Module.CurrentModule.AddInitialStateOption(new InitialStateOption("Options", new TextObject("{=NqarFr4P}Options"), 9998, (Action) (() => ScreenManager.PushScreen(ViewCreator.CreateOptionsScreen(true))), (Func<(bool, TextObject)>) (() => (false, TextObject.Empty))));
      Module.CurrentModule.AddInitialStateOption(new InitialStateOption("Credits", new TextObject("{=ODQmOrIw}Credits"), 9999, (Action) (() => ScreenManager.PushScreen(ViewCreator.CreateCreditsScreen())), (Func<(bool, TextObject)>) (() => (false, TextObject.Empty))));
      Module.CurrentModule.AddInitialStateOption(new InitialStateOption("Exit", new TextObject("{=YbpzLHzk}Exit Game"), 10000, (Action) (() => MBInitialScreenBase.DoExitButtonAction()), (Func<(bool, TextObject)>) (() => (Module.CurrentModule.IsOnlyCoreContentEnabled, coreContentDisabledReason))));
      Module.CurrentModule.ImguiProfilerTick += new Action(this.OnImguiProfilerTick);
      Input.OnControllerTypeChanged += new Action<Input.ControllerTypes>(this.OnControllerTypeChanged);
      NativeOptions.OnNativeOptionChanged += new NativeOptions.OnNativeOptionChangedDelegate(this.OnNativeOptionChanged);
      ViewModel.CollectPropertiesAndMethods();
      HyperlinkTexts.IsPlayStationGamepadActive = new Func<bool>(this.GetIsPlaystationGamepadActive);
      EngineController.OnConstrainedStateChanged += new Action<bool>(this.OnConstrainedStateChange);
    }

    private void OnConstrainedStateChange(bool isConstrained)
    {
      ScreenManager.OnConstrainStateChanged(isConstrained);
    }

    private bool GetIsPlaystationGamepadActive()
    {
      if (!Input.IsGamepadActive)
        return false;
      return Input.ControllerType == Input.ControllerTypes.PlayStationDualSense || Input.ControllerType == Input.ControllerTypes.PlayStationDualShock;
    }

    private void OnControllerTypeChanged(Input.ControllerTypes newType)
    {
      this.ReInitializeHotKeyManager();
    }

    private void OnNativeOptionChanged(
      NativeOptions.NativeOptionsType changedNativeOptionsType)
    {
      if (changedNativeOptionsType != NativeOptions.NativeOptionsType.EnableTouchpadMouse)
        return;
      this.ReInitializeHotKeyManager();
    }

    private void ReInitializeHotKeyManager() => this.InitializeHotKeyManager(true);

    protected override void OnSubModuleUnloaded()
    {
      ScreenManager.OnPushScreen -= new ScreenManager.OnPushScreenEvent(this.OnScreenManagerPushScreen);
      NativeOptions.OnNativeOptionChanged -= new NativeOptions.OnNativeOptionChangedDelegate(this.OnNativeOptionChanged);
      TableauCacheManager.ClearManager();
      BannerlordTableauManager.ClearManager();
      CraftedDataViewManager.Clear();
      Module.CurrentModule.ImguiProfilerTick -= new Action(this.OnImguiProfilerTick);
      Input.OnControllerTypeChanged -= new Action<Input.ControllerTypes>(this.OnControllerTypeChanged);
      ViewSubModule._instance = (ViewSubModule) null;
      EngineController.OnConstrainedStateChanged -= new Action<bool>(this.OnConstrainedStateChange);
      base.OnSubModuleUnloaded();
    }

    protected override void OnBeforeInitialModuleScreenSetAsRoot()
    {
      if (this._initialized)
        return;
      HotKeyManager.Load();
      BannerlordTableauManager.InitializeCharacterTableauRenderSystem();
      TableauCacheManager.InitializeManager();
      this._initialized = true;
    }

    protected override void OnApplicationTick(float dt)
    {
      base.OnApplicationTick(dt);
      if (Input.DebugInput.IsHotKeyPressed("ToggleUI"))
        MBDebug.DisableUI(new List<string>());
      HotKeyManager.Tick(dt);
      MBMusicManager.Current?.Update(dt);
      TableauCacheManager.Current?.Tick();
    }

    protected override void AfterAsyncTickTick(float dt) => MBMusicManager.Current?.Update(dt);

    protected override void OnGameStart(Game game, IGameStarter gameStarterObject)
    {
      MissionWeapon.OnGetWeaponDataHandler = new MissionWeapon.OnGetWeaponDataDelegate(ItemCollectionElementViewExtensions.OnGetWeaponData);
    }

    public override void OnCampaignStart(Game game, object starterObject)
    {
      Game.Current.GameStateManager.RegisterListener((IGameStateManagerListener) this._gameStateScreenManager);
      this._newGameInitialization = false;
    }

    public override void OnMultiplayerGameStart(Game game, object starterObject)
    {
      Game.Current.GameStateManager.RegisterListener((IGameStateManagerListener) this._gameStateScreenManager);
    }

    public override void OnGameLoaded(Game game, object initializerObject)
    {
      Game.Current.GameStateManager.RegisterListener((IGameStateManagerListener) this._gameStateScreenManager);
    }

    public override void OnGameInitializationFinished(Game game)
    {
      base.OnGameInitializationFinished(game);
      foreach (ItemObject objectType in (List<ItemObject>) Game.Current.ObjectManager.GetObjectTypeList<ItemObject>())
      {
        if (objectType.MultiMeshName != "")
          MBUnusedResourceManager.SetMeshUsed(objectType.MultiMeshName);
        HorseComponent horseComponent = objectType.HorseComponent;
        if (horseComponent != null)
        {
          foreach (KeyValuePair<string, bool> additionalMeshesName in horseComponent.AdditionalMeshesNameList)
            MBUnusedResourceManager.SetMeshUsed(additionalMeshesName.Key);
        }
        if (objectType.PrimaryWeapon != null)
        {
          MBUnusedResourceManager.SetMeshUsed(objectType.HolsterMeshName);
          MBUnusedResourceManager.SetMeshUsed(objectType.HolsterWithWeaponMeshName);
          MBUnusedResourceManager.SetMeshUsed(objectType.FlyingMeshName);
          MBUnusedResourceManager.SetBodyUsed(objectType.BodyName);
          MBUnusedResourceManager.SetBodyUsed(objectType.HolsterBodyName);
          MBUnusedResourceManager.SetBodyUsed(objectType.CollisionBodyName);
        }
      }
    }

    public override void BeginGameStart(Game game)
    {
      base.BeginGameStart(game);
      Game.Current.BannerVisualCreator = (IBannerVisualCreator) new BannerVisualCreator();
    }

    public override bool DoLoading(Game game)
    {
      if (this._newGameInitialization)
        return true;
      this._newGameInitialization = true;
      return this._newGameInitialization;
    }

    public override void OnGameEnd(Game game)
    {
      MissionWeapon.OnGetWeaponDataHandler = (MissionWeapon.OnGetWeaponDataDelegate) null;
      CraftedDataViewManager.Clear();
    }

    private void OnImguiProfilerTick() => TableauCacheManager.Current.OnImguiProfilerTick();

    private void OnScreenManagerPushScreen(ScreenBase pushedScreen)
    {
    }
  }
}
